package com.by.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.by.config.SystemConfig;
import com.by.config.SystemConfig.CurrencyType;
import com.by.config.SystemConfig.PointType;
import com.by.config.SystemConfig.RoundType;
import com.by.config.SystemConfig.StoreFreezeTime;
import com.by.config.SystemConfig.WatermarkPosition;

public class Util {
	
	/**
	 * 随机获取UUID字符串（不包含中划线）
	 * @return　String
	 */
	
	public static String getUUID(){
		String uuidStr = UUID.randomUUID().toString();
		
		return uuidStr.substring(0, 8)+uuidStr.substring(9,13)
			  +uuidStr.substring(14, 18)+uuidStr.substring(19,23)+uuidStr.substring(24);
		
	}
	
	
	
	/**
	 * 获取图片的类型
	 * @param file
	 * @return String
	 */
	
	public static String getImageFormatName(File file ){
		
		try {
			ImageInputStream imageInputStream = ImageIO.createImageInputStream(file);
			Iterator<ImageReader> iterator    = ImageIO.getImageReaders(imageInputStream);
			if(!iterator.hasNext()){
				return null;
			}
			ImageReader imageReader = iterator.next();
			imageInputStream.close();
			return imageReader.getFormatName().toLowerCase();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return null;
		
	}
	
	
	
	
	
	/**
	 * 此解析XML实例按照  D:\web\project\Jfinalblog\res\jfinalblog.xml 的格式解析
	 * SAXReader
	 * 
	 * @param filePath 文件路径
	 * @return
	 */
	public static SystemConfig getXML(String filePath){
		Document document = null;
		File file = new File(filePath);
		SAXReader saxReader = new SAXReader();
		try {
			document = saxReader.read(file);
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Node systemNameNode = document.selectSingleNode("/jfinalblog/systemConfig/systemName");
		Node systemVersionNode = document.selectSingleNode("/jfinalblog/systemConfig/systemVersion");
		Node systemDescriptionNode = document.selectSingleNode("/jfinalblog/systemConfig/systemDescription");
		Node isInstalledNode = document.selectSingleNode("/jfinalblog/systemConfig/isInstalled");
		Node shopNameNode = document.selectSingleNode("/jfinalblog/systemConfig/shopName");
		Node shopUrlNode = document.selectSingleNode("/jfinalblog/systemConfig/shopUrl");
		Node shopLogoNode = document.selectSingleNode("/jfinalblog/systemConfig/shopLogo");
		Node hotSearchNode = document.selectSingleNode("/jfinalblog/systemConfig/hotSearch");
		Node metaKeywordsNode = document.selectSingleNode("/jfinalblog/systemConfig/metaKeywords");
		Node metaDescriptionNode = document.selectSingleNode("/jfinalblog/systemConfig/metaDescription");
		Node addressNode = document.selectSingleNode("/jfinalblog/systemConfig/address");
		Node phoneNode = document.selectSingleNode("/jfinalblog/systemConfig/phone");
		Node zipCodeNode = document.selectSingleNode("/jfinalblog/systemConfig/zipCode");
		Node emailNode = document.selectSingleNode("/jfinalblog/systemConfig/email");
		Node currencyTypeNode = document.selectSingleNode("/jfinalblog/systemConfig/currencyType");
		Node currencySignNode = document.selectSingleNode("/jfinalblog/systemConfig/currencySign");
		Node currencyUnitNode = document.selectSingleNode("/jfinalblog/systemConfig/currencyUnit");
		Node priceScaleNode = document.selectSingleNode("/jfinalblog/systemConfig/priceScale");
		Node priceRoundTypeNode = document.selectSingleNode("/jfinalblog/systemConfig/priceRoundType");
		Node orderScaleNode = document.selectSingleNode("/jfinalblog/systemConfig/orderScale");
		Node orderRoundTypeNode = document.selectSingleNode("/jfinalblog/systemConfig/orderRoundType");
		Node certtextNode = document.selectSingleNode("/jfinalblog/systemConfig/certtext");
		Node storeAlertCountNode = document.selectSingleNode("/jfinalblog/systemConfig/storeAlertCount");
		Node storeFreezeTimeNode = document.selectSingleNode("/jfinalblog/systemConfig/storeFreezeTime");
		Node uploadLimitNode = document.selectSingleNode("/jfinalblog/systemConfig/uploadLimit");
		Node isLoginFailureLockNode = document.selectSingleNode("/jfinalblog/systemConfig/isLoginFailureLock");
		Node loginFailureLockCountNode = document.selectSingleNode("/jfinalblog/systemConfig/loginFailureLockCount");
		Node loginFailureLockTimeNode = document.selectSingleNode("/jfinalblog/systemConfig/loginFailureLockTime");
		Node isRegisterNode = document.selectSingleNode("/jfinalblog/systemConfig/isRegister");
		Node watermarkImagePathNode = document.selectSingleNode("/jfinalblog/systemConfig/watermarkImagePath");
		Node watermarkPositionNode = document.selectSingleNode("/jfinalblog/systemConfig/watermarkPosition");
		Node watermarkAlphaNode = document.selectSingleNode("/jfinalblog/systemConfig/watermarkAlpha");
		Node bigProductImageWidthNode = document.selectSingleNode("/jfinalblog/systemConfig/bigProductImageWidth");
		Node bigProductImageHeightNode = document.selectSingleNode("/jfinalblog/systemConfig/bigProductImageHeight");
		Node smallProductImageWidthNode = document.selectSingleNode("/jfinalblog/systemConfig/smallProductImageWidth");
		Node smallProductImageHeightNode = document.selectSingleNode("/jfinalblog/systemConfig/smallProductImageHeight");
		Node thumbnailProductImageWidthNode = document.selectSingleNode("/jfinalblog/systemConfig/thumbnailProductImageWidth");
		Node thumbnailProductImageHeightNode = document.selectSingleNode("/jfinalblog/systemConfig/thumbnailProductImageHeight");
		Node defaultBigProductImagePathNode = document.selectSingleNode("/jfinalblog/systemConfig/defaultBigProductImagePath");
		Node defaultSmallProductImagePathNode = document.selectSingleNode("/jfinalblog/systemConfig/defaultSmallProductImagePath");
		Node defaultThumbnailProductImagePathNode = document.selectSingleNode("/jfinalblog/systemConfig/defaultThumbnailProductImagePath");
		Node allowedUploadImageExtensionNode = document.selectSingleNode("/jfinalblog/systemConfig/allowedUploadImageExtension");
		Node allowedUploadMediaExtensionNode = document.selectSingleNode("/jfinalblog/systemConfig/allowedUploadMediaExtension");
		Node allowedUploadFileExtensionNode = document.selectSingleNode("/jfinalblog/systemConfig/allowedUploadFileExtension");
		Node smtpFromMailNode = document.selectSingleNode("/jfinalblog/systemConfig/smtpFromMail");
		Node smtpHostNode = document.selectSingleNode("/jfinalblog/systemConfig/smtpHost");
		Node smtpPortNode = document.selectSingleNode("/jfinalblog/systemConfig/smtpPort");
		Node smtpUsernameNode = document.selectSingleNode("/jfinalblog/systemConfig/smtpUsername");
		Node smtpPasswordNode = document.selectSingleNode("/jfinalblog/systemConfig/smtpPassword");
		Node pointTypeNode = document.selectSingleNode("/jfinalblog/systemConfig/pointType");
		Node pointScaleNode = document.selectSingleNode("/jfinalshop/systemConfig/pointScale");

		SystemConfig systemConfig = new SystemConfig();
		systemConfig.setSystemName(systemNameNode.getText());
		systemConfig.setSystemVersion(systemVersionNode.getText());
		systemConfig.setSystemDescription(systemDescriptionNode.getText());
		systemConfig.setIsInstalled(Boolean.valueOf(isInstalledNode.getText()));
		systemConfig.setShopName(shopNameNode.getText());
		systemConfig.setShopUrl(shopUrlNode.getText());
		systemConfig.setShopLogo(shopLogoNode.getText());
		systemConfig.setHotSearch(hotSearchNode.getText());
		systemConfig.setMetaKeywords(metaKeywordsNode.getText());
		systemConfig.setMetaDescription(metaDescriptionNode.getText());
		systemConfig.setAddress(addressNode.getText());
		systemConfig.setPhone(phoneNode.getText());
		systemConfig.setZipCode(zipCodeNode.getText());
		systemConfig.setEmail(emailNode.getText());
		systemConfig.setCurrencyType(CurrencyType.valueOf(currencyTypeNode.getText()).name());
		systemConfig.setCurrencySign(currencySignNode.getText());
		systemConfig.setCurrencyUnit(currencyUnitNode.getText());
		systemConfig.setPriceScale(Integer.valueOf(priceScaleNode.getText()));
		systemConfig.setPriceRoundType(RoundType.valueOf(priceRoundTypeNode.getText()).name());
		systemConfig.setOrderScale(Integer.valueOf(orderScaleNode.getText()));
		systemConfig.setOrderRoundType(RoundType.valueOf(orderRoundTypeNode.getText()).name());
		systemConfig.setCerttext(certtextNode.getText());
		systemConfig.setStoreAlertCount(Integer.valueOf(storeAlertCountNode.getText()));
		systemConfig.setStoreFreezeTime(StoreFreezeTime.valueOf(storeFreezeTimeNode.getText()).name());
		systemConfig.setUploadLimit(Integer.valueOf(uploadLimitNode.getText()));
		systemConfig.setIsLoginFailureLock(Boolean.valueOf(isLoginFailureLockNode.getText()));
		systemConfig.setLoginFailureLockCount(Integer.valueOf(loginFailureLockCountNode.getText()));
		systemConfig.setLoginFailureLockTime(Integer.valueOf(loginFailureLockTimeNode.getText()));
		systemConfig.setIsRegister(Boolean.valueOf(isRegisterNode.getText()));
		systemConfig.setWatermarkImagePath(watermarkImagePathNode.getText());
		systemConfig.setWatermarkPosition(WatermarkPosition.valueOf(watermarkPositionNode.getText()).name());
		systemConfig.setWatermarkAlpha(Integer.valueOf(watermarkAlphaNode.getText()));
		systemConfig.setBigProductImageWidth(Integer.valueOf(bigProductImageWidthNode.getText()));
		systemConfig.setBigProductImageHeight(Integer.valueOf(bigProductImageHeightNode.getText()));
		systemConfig.setSmallProductImageWidth(Integer.valueOf(smallProductImageWidthNode.getText()));
		systemConfig.setSmallProductImageHeight(Integer.valueOf(smallProductImageHeightNode.getText()));
		systemConfig.setThumbnailProductImageWidth(Integer.valueOf(thumbnailProductImageWidthNode.getText()));
		systemConfig.setThumbnailProductImageHeight(Integer.valueOf(thumbnailProductImageHeightNode.getText()));
		systemConfig.setDefaultBigProductImagePath(defaultBigProductImagePathNode.getText());
		systemConfig.setDefaultSmallProductImagePath(defaultSmallProductImagePathNode.getText());
		systemConfig.setDefaultThumbnailProductImagePath(defaultThumbnailProductImagePathNode.getText());
		systemConfig.setAllowedUploadImageExtension(allowedUploadImageExtensionNode.getText());
		systemConfig.setAllowedUploadMediaExtension(allowedUploadMediaExtensionNode.getText());
		systemConfig.setAllowedUploadFileExtension(allowedUploadFileExtensionNode.getText());
		systemConfig.setSmtpFromMail(smtpFromMailNode.getText());
		systemConfig.setSmtpHost(smtpHostNode.getText());
		systemConfig.setSmtpPort(Integer.valueOf(smtpPortNode.getText()));
		systemConfig.setSmtpUsername(smtpUsernameNode.getText());
		systemConfig.setSmtpPassword(smtpPasswordNode.getText());
		systemConfig.setPointType(PointType.valueOf(pointTypeNode.getText()).name());
		systemConfig.setPointScale(Double.valueOf(pointScaleNode.getText()));
		
	
		return systemConfig;
		
	}
	
    public static boolean isEmpty(String str){
		return str.trim().length() ==0 ||str==null;
    	
    }
  
	public static String Md5ecode(String password) throws UnsupportedEncodingException {
		
		   MessageDigest md5 = null;
	        try {
	            md5 = MessageDigest.getInstance("MD5");
	        } catch (Exception e) {
	            System.out.println(e.toString());
	            e.printStackTrace();
	            return "";
	        }

	        byte[] byteArray = password.getBytes("UTF-8");
	        byte[] md5Bytes = md5.digest(byteArray);
	        StringBuffer hexValue = new StringBuffer();
	        for (int i = 0; i < md5Bytes.length; i++) {
	            int val = ((int) md5Bytes[i]) & 0xff;
	            if (val < 16) {
	                hexValue.append("0");
	            }
	            hexValue.append(Integer.toHexString(val));
	        }
	        return hexValue.toString();
	}
   public static String  getNow() {
	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 Date date = new Date();
	 return sdf.format(date);
}
}
